package org.dahuatech.ssh.action;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.dahuatech.ssh.common.utils.ConstantsUtils;
import org.dahuatech.ssh.entity.account.User;
import org.dahuatech.ssh.service.account.AccountManager;
import org.springframework.beans.factory.annotation.Autowired;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
@Results( { 
	@Result(name = ActionSupport.SUCCESS, location = "index.action", type = "redirect") ,
	@Result(name = ActionSupport.INPUT, location = "/login.html", type = "redirect")})
public class LoginAction extends ActionSupport implements ModelDriven<User> {

	private User entity;
	
	private AccountManager accountManager;
	
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		User user=accountManager.findUser(entity);
		if(user!=null){
			entity=user;
			HttpSession session=ServletActionContext.getRequest().getSession();
			session.setAttribute(ConstantsUtils.USER, entity);
			return ActionSupport.SUCCESS;
		}else{
			this.addActionError("登录失败");
			return ActionSupport.INPUT;
		}
	}
	
	/**
	 * 退出系统
	 * @return
	 */
	@Action(value="logout")
	public String logout(){
		ServletActionContext.getRequest().getSession().invalidate();
		return ActionSupport.INPUT;
	}

	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		if(entity==null){
			entity=new User();
		}
		return entity;
	}

	public void setEntity(User entity) {
		this.entity = entity;
	}

	public User getEntity() {
		return entity;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	public AccountManager getAccountManager() {
		return accountManager;
	}

}
